<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '编辑' : '新增'"
    width="600"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="110"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="21">
          <el-form-item label="币种名称" prop="name">
            <el-input v-model.trim="form.name" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="3" class="mt-7">
          <el-form-item label="" label-width="0" prop="status">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="2"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
            />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="币种简称" prop="currency">
            <el-input v-model.trim="form.currency" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="排序">
            <el-input-number classs="w-full" v-model="form.sort" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="汇率类型" prop="exchange_type">
        <el-radio-group v-model="form.exchange_type">
          <el-radio :label="1">固定汇率</el-radio>
          <el-radio :label="2">实时汇率</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="固定汇率"
        :prop="form.exchange_type == 1 ? 'exchange_rate' : ''"
      >
        <el-input
          v-model="form.exchange_rate"
          oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,6}).*/,'$1')"
          placeholder="请输入对人民币汇率"
          clearable
        />
      </el-form-item>
      <el-form-item label="平台汇率">
        <el-table :data="form.base_currencys_platform" :row-class-name="rowClassName">
          <el-table-column prop="name" label="平台">
            <template #default="{ row }">
              <el-select class="w-full" v-model="row.platform_id" clearable>
                <el-option
                  v-for="(item, index) in platformOptions"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="平台汇率">
            <template #default="{ row }">
              <el-input
                v-model="row.platform_rate"
                placeholder="请输入"
                clearable
                oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,6}).*/,'$1')"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作" width="160">
            <template #default="{ row, $index }">
              <el-button type="primary" text @click="handleCreate()">新增</el-button>
              <el-button type="danger" text @click="handleDelete(row, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div class="text-gray-500">说明：选择实时汇率时，汇率不用填写，系统会自动同步</div>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { reactive, toRefs } from "vue";
import { ElMessage } from "element-plus";
import api from "../api";
import { platformOptions } from "../data.js";
import { filterDeleteFlag } from "@/utils/index.js";

const emits = defineEmits(["query"]);
const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  rules: {
    name: [{ required: true, message: "请输入币种名称" }],
    currency: [{ required: true, message: "请输入币种简称" }],
    exchange_rate: [{ required: true, message: "请输入汇率" }],
    exchange_type: [{ required: true, message: "请选择汇率类型", trigger: "blur" }],
  },
  load: false,
});
const { rules, form, visible, loading, formRef, load } = toRefs(data);
const open = async (id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  if (id) getDetail(id);
  visible.value = true;
};
const getDetail = (id) => {
  api.getDetail({ id }).then((res) => {
    form.value = res.data;
    if (form.value.base_currencys_platform.length) {
      form.value.base_currencys_platform = form.value.base_currencys_platform.map((i) => {
        if (i.platform_text == "ebay") {
          i.platform_id = 1;
        } else if (i.platform_text == "其他") {
          i.platform_id = 2;
        }
        return i;
      });
    } else {
      form.value.base_currencys_platform = [{}];
    }
  });
};
const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 新增校验平台重复的逻辑
      const duplicatePlatforms = findDuplicatePlatforms(
        form.value.base_currencys_platform
      );
      if (duplicatePlatforms.length > 0) {
        loading.value = false;
        ElMessage.error(`以下平台已存在：${duplicatePlatforms.join(", ")}`);
        return;
      }
      const formData = Object.assign({}, form.value);
      formData.base_currencys_platform = formData.base_currencys_platform.map((i) => {
        if (i.platform_id == 1) {
          i.platform_ids = [1];
          i.platform_text = "ebay";
        } else if (i.platform_id == 2) {
          i.platform_ids = [2, 3, 4, 99];
          i.platform_text = "其他";
        } else {
          i.platform_ids = [];
          i.platform_text = "";
        }
        return i;
      });

      formData.base_currencys_platform = formData.base_currencys_platform
        .filter((i) => {
          return i.id || (i.platform_rate && i.platform_id);
        })
        .map((i) => {
          if (i.id && !i.platform_rate && !i.platform_id) {
            return { ...i, delete: 1 };
          } else {
            return i;
          }
        });

      if (formData.id) {
        api
          .update(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        api
          .add(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

const initForm = () => {
  form.value = getForm();
};
// 初始化
const getForm = () => {
  return {
    name: "",
    status: 1,
    currency: "",
    exchange_type: "",
    exchange_rate: "",
    base_currencys_platform: [{}],
  };
};

onMounted(() => {
  initForm();
});

const close = () => {
  initForm();
  visible.value = false;
};
defineExpose({ open });

// 新增平台
const handleCreate = () => {
  form.value.base_currencys_platform.push({});
};

// 删除平台
const handleDelete = (item, index) => {
  if (filterDeleteFlag(form.value.base_currencys_platform)) {
    ElMessage.error("至少保留一条");
    return;
  }
  if (item.id) {
    item.delete = 1;
  } else {
    form.value.base_currencys_platform.splice(index, 1);
  }
};

// 检查并返回重复的平台ID列表
const findDuplicatePlatforms = (platformList) => {
  const platformIds = new Set();
  const duplicates = [];

  for (const item of platformList) {
    if (item.platform_id && platformIds.has(item.platform_id)) {
      duplicates.push(item.platform_id);
    } else {
      platformIds.add(item.platform_id);
    }
  }

  return duplicates;
};

const rowClassName = ({ row }) => {
  if (row.delete === 1) {
    return "hidden-row";
  }
  return "";
};
</script>
<style></style>
